<?php

namespace Admin\Controller;
use Common\Lib\Think\Page;
use Admin\Model\AdminModel;
use Common\Controller\AdminBaseController;

/**
 * 权限管理控制器
 */
class AuthManagerController extends AdminBaseController{

    const CNAME = '角色';

    protected $menu_model;
    protected $authRole_model;
    protected $authAccess_model;

    public function _initialize() {
        parent::_initialize();
        $this->menu_model       = D("Menu");
        $this->authRole_model   = D("AuthRole");
        $this->authAccess_model = D("AuthAccess");
        $this->assign('TITLE', self::CNAME);
    }

    /**
     * 管理员角色列表
     */
    public function index() {
        $keyword = I('post.keyword', '', 'htmlspecialchars');
        $where = array('status' => 1);
        if ($keyword) {
            $where['role_name'] = array( 'LIKE','%' . $keyword . '%');
            $this->assign('keyword', $keyword);
        }

        $count = $this->authRole_model->where($where)->count();
        $page = new Page($count, C('PAGE_LIST_ROWS'));
        $show = $page->show();
        $list = $this->authRole_model->where($where)->limit($page->firstRow . ',' . $page->listRows)->select();

        $this->assign('list', $list); // 赋值数据集
        $this->assign('page', $show); // 赋值分页输出
        $this->assign('count', $count);
        $this->display(); // 输出模板
    }

    /**
     * 添加管理员角色
     */
    public function add() {
        if (IS_POST) {
            $data = $this->authRole_model->create();
            if ($data) {
                $id = $this->authRole_model->add($data);
                if ($id) {
                    $this->success('添加成功', U('index'));
                } else {
                    $this->error('添加失败');
                }
            } else {
                $this->error($this->authRole_model->getError());
            }
        } else {
            $this->display();
        }
    }

    /**
     * 编辑管理员角色
     */
    public function edit() {
        $role_id = I('role_id', 0, 'intval');

        if ($role_id == AdminModel::DEFAULT_ADMIN_ROLE) {
            $this->error("超级管理员角色不能被修改");
        }

        if (IS_POST) {
            $data = $this->authRole_model->create();
            if ($data) {
                if ($this->authRole_model->save($data) !== false) {
                    $this->success('编辑成功', U('index'));
                } else {
                    $this->error('编辑失败');
                }
            } else {
                $this->error($this->authRole_model->getError());
            }
        } else {
            $detail = $this->authRole_model->find($role_id);
            $this->assign('detail', $detail);
            $this->display();
        }
    }

    /**
     * 删除管理员角色
     */
    public function delete() {
        $role_id = I('post.role_id', 0, 'intval');
        if ($role_id == AdminModel::DEFAULT_ADMIN_ROLE) {
            $this->error("超级管理员角色不能被修改");
        }
        $count = M('AuthRoleUser')->where(array('role_id' => $role_id))->count();
        if($count > 0) {
            $this->error('该角色下存在用户，请先删除角色下的所有用户');
        } else {
            $status = $this->authRole_model->delete($role_id);
            if ($status) {
                $this->success('删除成功', U('index'));
            } else {
                $this->error('删除失败');
            }
        }
    }

    /**
     * 角色授权
     */
    public function auth() {

        $role_id = I('role_id',0,'intval');
        if(empty($role_id)){
            $this->error('需要授权的角色不存在');
        }
        if (IS_POST) {
            $auth_ids = I('post.auth_ids');
            if (is_array($auth_ids) && count($auth_ids) > 0) {
                sort($auth_ids);
                array_unique($auth_ids);
                $this->authAccess_model->where(array("role_id" => $role_id,'type' => 'admin_url'))->delete();
                $parent_ids = $this->menu_model->where(array("menu_id" => array('IN', $auth_ids)))->getField('parent_id', true);
                $auth_ids = array_merge($auth_ids, array_unique($parent_ids));


                foreach ($auth_ids as $menu_id) {
                    $menu=$this->menu_model->where(array("menu_id" => $menu_id))->field("app,controller,action")->find();
                    if($menu){
                        $app         = $menu['app'];
                        $controller  = $menu['controller'];
                        $action      = $menu['action'];
                        $name        = strtolower("$app/$controller/$action");
                        $this->authAccess_model->add(array('role_id' => $role_id, 'rule_name' => $name, 'type' => 'admin_url'));
                    }
                }
                $this->success('授权成功', U('index'));
            } else {
                //当没有数据时，清除当前角色授权
                $this->authAccess_model->where(array('role_id' => $role_id))->delete();
                $this->error("没有接收到数据，执行清除授权成功");
            }
        } else {
            $detail  = $this->authRole_model->find($role_id);

            $access_rules = $this->authAccess_model->where(array('role_id' => $role_id))->getField('rule_name',true);//获取权限表数据
            $menus     = $this->menu_model->fetchAll();
            $auth_ids = $this->_get_auth_ids($menus, $access_rules);

            $this->assign('auths', $menus);
            $this->assign('authIds', $auth_ids);
            $this->assign('role_id', $role_id);
            $this->assign('detail', $detail);
            $this->display();
        }
    }

    /**
     *  检查指定菜单是否有权限
     * @param array $menu menu表中数组
     * @param array access_rules 角色已授权的规则
     */
    private function _get_auth_ids($menus, $access_rules)
    {
        $auth_ids = array();
        foreach ($menus as $menu) {
            $app         = $menu['app'];
            $controller  = $menu['controller'];
            $action      = $menu['action'];
            $name        = strtolower("$app/$controller/$action");
            if (!empty($access_rules) && in_array($name, $access_rules)) {
                array_push($auth_ids, $menu['menu_id']);
            }
        }
        return $auth_ids;
    }
}